var dbConfig = require('../../util/dbconfig');
var moment = require('moment');
const fs = require("fs");
const path = require("path");
const formidable = require('formidable');
//查询物品
getThisngs = async (req, res) => {
	if (req.query.number >= 1) { //分页器查询数据库
		req.query.number = (req.query.number - 1) * req.query.size
	}
	if (req.query.type == "search") {
		if (req.query.query == '') {
			var sql =
				`select * from things  LIMIT ${req.query.number},${req.query.size}`;
		} else {
				var sql =
					`select * from things where name like "%${req.query.query}%" LIMIT ${req.query.number},${req.query.size}`;
		}
	}
	var sqlArr = [];
	let number;
	if(!req.query.query.length){//没有参数，走true
		 number = (await getUserAllNumber(1))[0].number;
	}else{
		 number = (await getUserAllNumber(0,req.query.query))[0].number;
	}
	var cb = async (err, data) => {
		res.send({
			"data": data,
			"number": number,
			"code": 200,
			"text": "列表获取成功"
		})
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}
function getUserAllNumber(flag,rules=null) {
	if(flag==1){
		var sql = `SELECT COUNT(*) number FROM things`;
	}else{
		var sql = `SELECT COUNT(*) number FROM things where name like "%${rules}%"`;
	}
	var sqlArr = [];
	return dbConfig.SySqlConnect(sql, sqlArr);
}

delthings = async (req, res) => {
	if (req.user.userName !== "admin") {
		res.send({
			"code": 0,
			"text": "没有权限"
		})
	} else {
		let sql = `DELETE FROM things WHERE Id='${req.body.Id}'`;
		let sqlArr = [];
		let data = await dbConfig.SySqlConnect(sql, sqlArr);
		if (data.affectedRows == 1) {
			res.send({
				"code": 201,
				"text": "删除成功"
			})
		}
	}
}
updateImg = (req, res) => {
	var form = new formidable.IncomingForm();
	form.encoding = 'utf-8';
	form.uploadDir = path.join((path.resolve(__dirname, '../../') + "/public/images"));
	form.keepExtensions = true; //保留后缀
	form.maxFieldsSize = 2 * 1024 * 1024;
	//处理图片
	form.parse(req, function(err, fields, files) {
		var filename = files.file.path;
		var nameArray = filename.split('.');
		var type = nameArray[nameArray.length - 1];
		var name = '';
		for (var i = 0; i < nameArray.length - 1; i++) {
			name = name + nameArray[i];
		}
		var d = new Date();
		var m = d.getMinutes();
		var s = d.getSeconds();
		m = checkTime(m);
		s = checkTime(s);

		function checkTime(i) {
			if (i < 10) {
				i = "0" + i
			}
			return i
		}
		var time = d.getFullYear() + '_' + (d.getMonth() + 1) + '_' + d.getDate() + '_' + d.getHours() + '_' + m + '_' + s +
			'-' + `${req.data.userName}`;
		var avatarName = name + time + '.' + type;
		var newPath = avatarName;
		fs.renameSync(files.file.path, newPath); //重命名
		newPath = newPath.split("images\\");
		res.send({
			data:"/public/images/"+newPath[1],
			text: '上传成功',
			code: 200
		})
	})
}
imgUpload= (req,res)=>{
	var form = new formidable.IncomingForm();
	form.encoding = 'utf-8';
	form.uploadDir = path.join((path.resolve(__dirname, '../../') + "/public/thingsdetail"));
	form.keepExtensions = true; //保留后缀
	form.maxFieldsSize = 2 * 1024 * 1024;
	//处理图片
	form.parse(req, function(err, fields, files) {
		var filename = files.file.path;
		var nameArray = filename.split('.');
		var type = nameArray[nameArray.length - 1];
		var name = '';
		for (var i = 0; i < nameArray.length - 1; i++) {
			name = name + nameArray[i];
		}
		var avatarName = name + '.' + type;
		var newPath = avatarName;
		fs.renameSync(files.file.path, newPath); //重命名
		console.log(newPath);
		newPath = newPath.split("thingsdetail\\");
		res.send({
			data:"/public/thingsdetail/"+newPath[1],
			text: '上传成功',
			code: 200
		})
	})
}
addthings = async (req, res) => {
	var date = moment().format("YYYY-MM-DD HH:mm:ss");
	let base = req.body;
	let sql =
		`insert into things(name,price,agoprice,buynum,detailinfo,imgs,addTime,browsenum,num) value(?,?,?,?,?,?,?,?,?)`;
	let sqlArr = [base.name,base.price,base.agoprice,base.buynum,base.content,base.imgs,date,base.browsenum,base.num];
	let data = await dbConfig.SySqlConnect(sql, sqlArr);
	if (data.affectedRows == 1) {
		res.send({
			"code": 201,
			"text": "添加数据成功"
		})
	} else {
		return res.send({
			"text":"addthings错误",
			"code":500
		})
	}
}
updatethings =async(req,res)=>{
	let base = req.body;
	var date = moment().format("YYYY-MM-DD HH:mm:ss");
	let sql = `update things set name='${base.name}', addTime='${date}',num='${base.num}',price = '${base.price}', agoprice = '${base.agoprice}', buynum='${base.buynum}', imgs='${base.imgsArr}',detailinfo='${base.content}',browsenum='${base.browsenum}' where id=${base.id}`;
	  let sqlArr=[];
		let data = await dbConfig.SySqlConnect(sql,sqlArr);
		if(data.affectedRows == 1){
			res.send({
				"code": 201,
				"text": "更改数据成功"
			})
		}else{
			res.send({
				"code": 0,
				"text": "更改数据失败"
			})
		}
}
module.exports = {
	getThisngs,
	delthings,
	updateImg,
	imgUpload,
	addthings,
	updatethings
}
